
class Game {
    constructor() {
        this.canvas = document.getElementById('gameCanvas');
        this.ctx = this.canvas.getContext('2d');
        this.scoreElement = document.getElementById('score');
        this.finalScoreElement = document.getElementById('finalScore');
        this.gameOverModal = document.getElementById('gameOverModal');
        
        // 游戏状态
        this.isRunning = false;
        this.isPaused = false;
        this.score = 0;
        this.gameSpeed = 2;
        
        // 玩家小球
        this.player = {
            x: this.canvas.width / 2,
            y: this.canvas.height - 50,
            radius: 15,
            speed: 5,
            color: '#4CAF50'
        };
        
        // 障碍物数组
        this.obstacles = [];
        
        // 键盘状态
        this.keys = {};
        
        // 绑定事件
        this.bindEvents();
        
        // 初始化画布大小
        this.resizeCanvas();
        window.addEventListener('resize', () => this.resizeCanvas());
    }
    
    bindEvents() {
        // 按钮事件
        document.getElementById('startBtn').addEventListener('click', () => this.startGame());
        document.getElementById('pauseBtn').addEventListener('click', () => this.togglePause());
        document.getElementById('resetBtn').addEventListener('click', () => this.resetGame());
        document.getElementById('playAgainBtn').addEventListener('click', () => {
            this.hideGameOverModal();
            this.resetGame();
            this.startGame();
        });
        
        // 键盘事件
        document.addEventListener('keydown', (e) => {
            this.keys[e.key] = true;
        });
        
        document.addEventListener('keyup', (e) => {
            this.keys[e.key] = false;
        });
        
        // 触摸事件（移动端支持）
        this.canvas.addEventListener('touchstart', (e) => {
            e.preventDefault();
            const touch = e.touches[0];
            const rect = this.canvas.getBoundingClientRect();
            const x = touch.clientX - rect.left;
            
            if (x < this.canvas.width / 2) {
                this.keys['ArrowLeft'] = true;
            } else {
                this.keys['ArrowRight'] = true;
            }
        });
        
        this.canvas.addEventListener('touchend', (e) => {
            e.preventDefault();
            this.keys['ArrowLeft'] = false;
            this.keys['ArrowRight'] = false;
        });
    }
    
    resizeCanvas() {
        const maxWidth = Math.min(window.innerWidth - 40, 800);
        const aspectRatio = 800 / 600;
        this.canvas.width = maxWidth;
        this.canvas.height = maxWidth / aspectRatio;
        
        // 重新设置玩家位置
        if (this.player) {
            this.player.y = this.canvas.height - 50;
        }
    }
    
    startGame() {
        if (!this.isRunning) {
            this.isRunning = true;
            this.isPaused = false;
            document.getElementById('startBtn').disabled = true;
            document.getElementById('pauseBtn').disabled = false;
            this.gameLoop();
        }
    }
    
    togglePause() {
        if (this.isRunning) {
            this.isPaused = !this.isPaused;
            document.getElementById('pauseBtn').textContent = this.isPaused ? '继续' : '暂停';
            if (!this.isPaused) {
                this.gameLoop();
            }
        }
    }
    
    resetGame() {
        this.isRunning = false;
        this.isPaused = false;
        this.score = 0;
        this.gameSpeed = 2;
        this.obstacles = [];
        this.player.x = this.canvas.width / 2;
        this.player.y = this.canvas.height - 50;
        
        document.getElementById('startBtn').disabled = false;
        document.getElementById('pauseBtn').disabled = true;
        document.getElementById('pauseBtn').textContent = '暂停';
        
        this.updateScore();
        this.clearCanvas();
        this.drawPlayer();
    }
    
    gameLoop() {
        if (!this.isRunning || this.isPaused) return;
        
        this.update();
        this.draw();
        
        requestAnimationFrame(() => this.gameLoop());
    }
    
    update() {
        // 更新玩家位置
        this.updatePlayer();
        
        // 生成新障碍物
        if (Math.random() < 0.02) {
            this.createObstacle();
        }
        
        // 更新障碍物位置
        this.updateObstacles();
        
        // 检测碰撞
        this.checkCollisions();
        
        // 增加游戏难度
        if (this.score > 0 && this.score % 100 === 0) {
            this.gameSpeed += 0.1;
        }
    }
    
    updatePlayer() {
        if (this.keys['ArrowLeft'] && this.player.x - this.player.radius > 0) {
            this.player.x -= this.player.speed;
        }
        if (this.keys['ArrowRight'] && this.player.x + this.player.radius < this.canvas.width) {
            this.player.x += this.player.speed;
        }
    }
    
    createObstacle() {
        const obstacle = {
            x: Math.random() * (this.canvas.width - 40) + 20,
            y: -30,
            width: 30 + Math.random() * 20,
            height: 30 + Math.random() * 20,
            speed: this.gameSpeed + Math.random() * 2,
            color: `hsl(${Math.random() * 360}, 70%, 50%)`
        };
        this.obstacles.push(obstacle);
    }
    
    updateObstacles() {
        for (let i = this.obstacles.length - 1; i >= 0; i--) {
            const obstacle = this.obstacles[i];
            obstacle.y += obstacle.speed;
            
            // 移除超出画布的障碍物并增加分数
            if (obstacle.y > this.canvas.height) {
                this.obstacles.splice(i, 1);
                this.score += 10;
                this.updateScore();
            }
        }
    }
    
    checkCollisions() {
        for (const obstacle of this.obstacles) {
            // 简化的矩形与圆形碰撞检测
            const closestX = Math.max(obstacle.x, Math.min(this.player.x, obstacle.x + obstacle.width));
            const closestY = Math.max(obstacle.y, Math.min(this.player.y, obstacle.y + obstacle.height));
            
            const distanceX = this.player.x - closestX;
            const distanceY = this.player.y - closestY;
            const distanceSquared = distanceX * distanceX + distanceY * distanceY;
            
            if (distanceSquared < this.player.radius * this.player.radius) {
                this.gameOver();
                return;
            }
        }
    }
    
    gameOver() {
        this.isRunning = false;
        this.finalScoreElement.textContent = this.score;
        this.showGameOverModal();
    }
    
    showGameOverModal() {
        this.gameOverModal.style.display = 'block';
    }
    
    hideGameOverModal() {
        this.gameOverModal.style.display = 'none';
    }
    
    updateScore() {
        this.scoreElement.textContent = this.score;
    }
    
    draw() {
        this.clearCanvas();
        this.drawPlayer();
        this.drawObstacles();
    }
    
    clearCanvas() {
        this.ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
    }
    
    drawPlayer() {
        this.ctx.beginPath();
        this.ctx.arc(this.player.x, this.player.y, this.player.radius, 0, Math.PI * 2);
        this.ctx.fillStyle = this.player.color;
        this.ctx.fill();
        this.ctx.strokeStyle = '#fff';
        this.ctx.lineWidth = 2;
        this.ctx.stroke();
        
        // 添加光晕效果
        this.ctx.beginPath();
        this.ctx.arc(this.player.x, this.player.y, this.player.radius + 5, 0, Math.PI * 2);
        this.ctx.strokeStyle = 'rgba(76, 175, 80, 0.3)';
        this.ctx.lineWidth = 3;
        this.ctx.stroke();
    }
    
    drawObstacles() {
        for (const obstacle of this.obstacles) {
            this.ctx.fillStyle = obstacle.color;
            this.ctx.fillRect(obstacle.x, obstacle.y, obstacle.width, obstacle.height);
            
            // 添加边框
            this.ctx.strokeStyle = '#fff';
            this.ctx.lineWidth = 2;
            this.ctx.strokeRect(obstacle.x, obstacle.y, obstacle.width, obstacle.height);
        }
    }
}

// 初始化游戏
window.addEventListener('DOMContentLoaded', () => {
    const game = new Game();
});
